<?php

namespace App\Http\Controllers\AgentAdmin;

use App\Enums\ProductStatus;
use App\Enums\ProductType;
use App\Enums\TokenStatus;
use App\Http\Controllers\Controller;
use App\Models\AgentUser;
use App\Models\Airdrop;
use App\Models\BlindBoxItem;
use App\Models\BlindBoxRecord;
use App\Models\FrontendUser;
use App\Models\Product;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Vinlon\Laravel\LayAdmin\Exceptions\AdminException;
use Vinlon\Laravel\LayAdmin\PaginateResponse;

class AirdropBlindBoxController extends Controller
{
    /**
     * 盲盒空投记录.
     */
    public function index(): PaginateResponse
    {
        /** @var AgentUser $user */
        $user = auth()->user();

        $query = Airdrop::query()
            ->where('agent_id', $user->agent_id)
            ->where('type', ProductType::BLIND_BOX)
            ->when(request()->keyword, function ($q) {
                return $q->where(function ($q1) {
                    $likeVal = '%' . request()->keyword . '%';

                    return $q1->where('nickname', 'like', $likeVal)->orWhere('mobile', 'like', $likeVal)->orWhere('goods_name', 'like', $likeVal);
                });
            })
            ->when(request()->status, function ($q) {
                if (3 == request()->status) {
                    request()->status = 0;
                }

                return $q->where('status', request()->status);
            })
            ->when(request()->start_date, function ($q) {
                $q->whereDate('created_at', '>=', request()->start_date);
            })
            ->when(request()->end_date, function ($q) {
                $q->whereDate('created_at', '<=', request()->end_date);
            })
            ->orderByDesc('id');

        return paginate_result($query);
    }

    public function store()
    {
        $data = request()->all();

        DB::transaction(function () use ($data) {
            /** @var AgentUser $loginUser */
            $loginUser = auth()->user();
            $errorFlag = false;
            $batchRecords = [];
            $errorMsg = '';
            foreach ($data['mobile'] as $k => $v) {
                if (empty($v) || empty($data['goods_id'][$k]) || empty($data['number'][$k])) {
                    $errorFlag = true;
                    $errorMsg .= '商品id、手机号、数量不能为空';

                    throw new AdminException($errorMsg);
                }

                if ($data['number'][$k] > 50) {
                    $errorMsg .= '数量不能大于50';

                    throw new AdminException($errorMsg);
                }

                $user = FrontendUser::query()->where('mobile', $v)->where('agent_id', $loginUser->agent_id)->first();

                if (empty($user)) {
                    $errorFlag = true;
                    $errorMsg .= '手机号' . $v . ',找不到用户;';

                    throw new AdminException($errorMsg);
                }

                /** @var Product $goods */
                $goods = Product::query()
                    ->where('type', ProductType::BLIND_BOX)
                    ->where('id', $data['goods_id'][$k])
                    ->where('agent_id', $loginUser->agent_id)->first();

                if (empty($goods)) {
                    $errorFlag = true;
                    $errorMsg .= '商品id' . $data['goods_id'][$k] . ',找不到对应商品;';

                    throw new AdminException($errorMsg);
                }
                if (ProductStatus::ON_SALE == $goods->status) {
                    $errorFlag = true;
                    $errorMsg .= '商品id' . $data['goods_id'][$k] . ',发行状态不支持空投;';

                    throw new AdminException($errorMsg);
                }
                if ($goods->left_count < $data['number'][$k]) {
                    $errorFlag = true;
                    $errorMsg .= '商品id' . $data['goods_id'][$k] . ',商品库存不足;';

                    throw new AdminException($errorMsg);
                }

                $order_sn = date('YmdHis') . mt_rand(1000000, 9999999);

                $save_data = [
                    'agent_id' => $user->agent_id,
                    'order_sn' => $order_sn,
                    'mobile' => $v,
                    'goods_id' => $data['goods_id'][$k],
                    'number' => $data['number'][$k],
                    'nickname' => $user->nickname,
                    'goods_name' => $goods->name,
                    'goods_img' => $goods->logo_url,
                    'tokenIds' => '',
                    'qianbao' => '',
                    'status' => 1,
                    'type' => ProductType::BLIND_BOX,
                    'created_at' => date('Y-m-d H:i:s'),
                ];
                Airdrop::create($save_data);

                // 库存更新
                $goods->decrement('left_count', $data['number'][$k]);
                $goods->increment('sales_count', $data['number'][$k]);

                /** @var BlindBoxItem[] $blindBoxItems */
                $blindBoxItems = BlindBoxItem::query()
                    ->with(['product_token'])
                    ->where('blind_box_id', $goods->id)->where('status', TokenStatus::INIT)
                    ->limit($data['number'][$k])
                    ->orderBy('sequence')->get();

                foreach ($blindBoxItems as $blindBoxItem) {
                    $batchRecords[] = [
                        'user_id' => $user->id,
                        'order_id' => 0,
                        'blind_box_id' => $goods->id,
                        'asset_product_id' => $blindBoxItem->product_id,
                        'asset_token_id' => $blindBoxItem->product_token->token_id,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ];
                }

                BlindBoxItem::query()->whereIn('id', Arr::pluck($blindBoxItems, 'id'))->update([
                    'status' => TokenStatus::SOLD(),
                ]);
            }

            BlindBoxRecord::query()->insert($batchRecords);
        });
    }
}
